package cn.com.winning.ecare.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import cn.com.winning.ecare.common.MyApplication;
import cn.com.winning.ecare.common.PullDownView;
import cn.com.winning.ecare.common.PullDownView.OnPullDownListener;
import cn.com.winning.ecare.utils.HTTPGetTool;
import cn.com.winning.ecare.utils.URLUtils;

/**商品信息
 * @author Administrator
 *
 */
public class Shop2 extends Activity implements OnPullDownListener , OnItemClickListener{

	private PullDownView mPullDownView;
	private Shop2 oThis = this;
	private ListView mListView;
	private MyAdapter mAdapter;
	List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
	private Map<String, Object> map;

	private int pc = 0;
	private List<Integer> list_buy;
	private MyApplication myApp;
	private String index;
	private String lbId;
	private List<Map<String, Object>> list_gwc;
	public static Shop2 instance = null;  
//    private TextView tv_lb;
//    private ImageButton backButton;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		//////设置shop2的大小及位置，露出主页面底部的按钮
//		WindowManager m = getWindowManager();
//		Display d = m.getDefaultDisplay(); // 为获取屏幕宽、高

//		WindowManager.LayoutParams p = getWindow().getAttributes(); // 获取对话框当前的参数值
//		p.height = (int) (d.getHeight() - DisplayUtil.dip2px(this, 60)); // 高度设置
//		p.width = (int) (d.getWidth()); // 宽度设置为屏幕的1
//		//p.alpha = 1.0f; // 设置本身透明度
//		//p.dimAmount = 0.0f; // 设置黑暗度
//		getWindow().setAttributes(p); // 设置生效
//		getWindow().setGravity(Gravity.TOP); // 设置靠上对齐
//////////////////////////////////////用于设置activity外点击事件，API11之前只能这样
//		getWindow().setFlags(p.FLAG_NOT_TOUCH_MODAL, p.FLAG_NOT_TOUCH_MODAL);
//		getWindow().setFlags(p.FLAG_WATCH_OUTSIDE_TOUCH, p.FLAG_WATCH_OUTSIDE_TOUCH);
		/////////
		setContentView(R.layout.shop2_main);
		MyApplication myApplication;
		myApplication = (MyApplication) getApplication();
		myApplication.addActivity(this);
		
		instance = this;
		// 初始化view
		findView();

		// 初始化界面数据
		GetData();

		// 设置监听事件
		setListener();

	}

	 
	private void findView() {
		// list_buy = new ArrayList<Integer>();
//		tv_lb = (TextView)findViewById(R.id.tv_type);
//		backButton = (ImageButton)this.findViewById(R.id.backButton);
		Intent intent = this.getIntent();
		if (intent != null) {
			String lb  = intent.getStringExtra("lb").trim();
//			tv_lb.setText(lb);
			lbId = intent.getStringExtra("lbid").trim();
			index = intent.getStringExtra("index").trim();
		}

		myApp = (MyApplication) getApplication();
		List[] list_gwcs = myApp.getList_gwc();
		List[] list_positons = myApp.getList_position();
		list_gwc = list_gwcs[Integer.parseInt(index)];
		list_buy = list_positons[Integer.parseInt(index)];
		Log.i("bbb", "" + myApp.getList_gwc().length);

		/*
		 * 1.使用PullDownView 2.设置OnPullDownListener 3.从mPullDownView里面获取ListView
		 */
		mPullDownView = (PullDownView) findViewById(R.id.pull_down_view);
		mPullDownView.setOnPullDownListener(this);
		mListView = mPullDownView.getListView();
		mListView.setDivider(getResources().getDrawable(R.color.divider_color));
		mListView.setDividerHeight(2);

		// 请求页数
		// count = 2;

		// ListView设置适配器
		// mAdapter = new SimpleAdapter(this, list, R.layout.shop3_sub,
		// new String[] { "xx" }, new int[] { R.id.tv_xx });
		// mListView.setAdapter(mAdapter);
		mAdapter = new MyAdapter(this);
		mAdapter.setList(list);

		mListView.setAdapter(mAdapter);

//		mPullDownView.enableAutoFetchMore(true, 1);

	}

	private void setListener() {
//		backButton.setOnClickListener(new View.OnClickListener() {
//
//			@Override
//			public void onClick(View v) {
//				// TODO Auto-generated method stub
//				
//				Shop2.this.onBackPressed();
//
//			}
//		});
//		
	}

	private void GetData() {
		new Thread(new LoadData()).start();
	}

	class LoadData implements Runnable {

		public void run() {
			// TODO Auto-generated method stub
			Looper.prepare();
			iniData();
			Looper.loop();
		}
	}

	private void iniData() {
		try {
			Message msg = mUIHandler.obtainMessage();
			Bundle bundle = new Bundle();
			List<NameValuePair> ls = new ArrayList<NameValuePair>();
			ls.add(new BasicNameValuePair("id", lbId));
			ls.add(new BasicNameValuePair("pc", String.valueOf(pc)));

			JSONObject json = HTTPGetTool.getTool().post(
					URLUtils.HOST + URLUtils.SPXXNAME, ls);

			if (json != null && !json.equals("")) {
				if (!json.toString().equals(
						"{\"msg\":\"系统错误！\",\"success\":\"false\"}")) {
					if (new JSONArray(json.getString("spxxinfo")).length()>0) {
						// 获取收费信息
						JSONArray jsonArr = new JSONArray(
								json.getString("spxxinfo"));
						JSONObject js = null;
						for (int i = 0; i < jsonArr.length(); i++) {
							Map<String, Object> map = new HashMap<String, Object>();
							js = jsonArr.getJSONObject(i);
							
							map.put("name", js.getString("spname"));
							map.put("price", js.getString("price"));
							map.put("dw", js.getString("dw"));
							map.put("imgpath", js.getString("imgpath"));
							map.put("lbid", js.getString("lbid"));
							map.put("spid", js.getString("id"));
							String strId = js.getString("id");
							
							// 获取图片
							List<NameValuePair> ls1 = new ArrayList<NameValuePair>();
							ls1.add(new BasicNameValuePair("id", strId));
							Bitmap bitmap = HTTPGetTool.getTool()
									.queryByteForPost(
											URLUtils.HOST + URLUtils.SPXXPIC,
											ls1);
							map.put("pic", bitmap);
							list.add(map);
						}

						bundle.putInt("type", 0);
						bundle.putString("msg", "");
						pc += 1;
					} else {
						bundle.putInt("type", -1);
						bundle.putString("msg", "暂无数据");
					}

				} else {
					bundle.putInt("type", -1);
					bundle.putString("msg", "系统错误");
				}

			} else {
				bundle.putInt("type", -1);
				bundle.putString("msg", "网络连接失败!");
			}
			msg.setData(bundle);
			mUIHandler.sendMessage(msg);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			// 捕捉异常
			Bundle bundle = new Bundle();
			bundle.putInt("type", -1);
			bundle.putString("msg", e.toString());
			Message msg = mUIHandler.obtainMessage();
			msg.setData(bundle);
			mUIHandler.sendMessage(msg);
		}
		
		
	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		new Thread(new Runnable() {

			@Override
			public void run() {
				Log.i("bbb", "onRefresh");
				Bundle bundle = new Bundle();
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				bundle.putInt("type", 1);
				bundle.putString("msg", "");
				Message msg = mUIHandler.obtainMessage();
				msg.setData(bundle);
				mUIHandler.sendMessage(msg);

			}
		}).start();

	}

	private Handler mUIHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			int type = msg.getData().getInt("type");
			switch (type) {
			case -1:
				// proDialog.dismiss();
				Toast.makeText(oThis, msg.getData().getString("msg"),
						Toast.LENGTH_SHORT).show();
				// 刷新
				mAdapter.notifyDataSetChanged();
				onLoad();
				break;
			case 0: {
				// proDialog.dismiss();
				mAdapter.notifyDataSetChanged();
				// 诉它数据加载完毕;
				onLoad();
				break;
			}
			case 1: {
				// addData("refresh");
				mAdapter.notifyDataSetChanged();
				// 告诉它更新完毕
				onLoad();
				break;
			}

			case 2: {
				// addData();
				mAdapter.notifyDataSetChanged();
				// 告诉它获取更多完毕
				onLoad();
				break;
			}
			}

		}

	};
	
	private void onLoad()
	{
		mPullDownView.notifyDidLoad();
		mPullDownView.notifyDidRefresh();
		mPullDownView.notifyDidMore();
		mPullDownView.enableAutoFetchMore(true, 1);
	}

	@Override
	public void onMore() {
		// TODO Auto-generated method stub

		new Thread(new Runnable() {

			@Override
			public void run() {
				Bundle bundle = new Bundle();
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				addData();
				// bundle.putInt("type", 2);
				// bundle.putString("msg", "");
				// Message msg = mUIHandler.obtainMessage();
				// msg.setData(bundle);
				// mUIHandler.sendMessage(msg);

			}
		}).start();

	}

	private void addData() {
		try {
			Message msg = mUIHandler.obtainMessage();
			Bundle bundle = new Bundle();
			List<NameValuePair> ls = new ArrayList<NameValuePair>();
			ls.add(new BasicNameValuePair("id", lbId));
			ls.add(new BasicNameValuePair("pc", String.valueOf(pc)));
			
			JSONObject json = HTTPGetTool.getTool().post(
					URLUtils.HOST + URLUtils.SPXXNAME, ls);

			if (json != null && !json.equals("")) {
				if (!json.toString().equals(
						"{\"msg\":\"系统错误！\",\"success\":\"false\"}")) {
					if (!json.getString("spxxs").equals("")) {
						// 获取收费信息
						JSONArray jsonArr = new JSONArray(
								json.getString("spxxinfo"));
						JSONObject js = null;
						for (int i = 0; i < jsonArr.length(); i++) {
							Map<String, Object> map = new HashMap<String, Object>();
							js = jsonArr.getJSONObject(i);
							
							map.put("name", js.getString("spname"));
							map.put("price", js.getString("price"));
							map.put("dw", js.getString("dw"));
							map.put("imgpath", js.getString("imgpath"));
							map.put("lbid", js.getString("lbid"));
							map.put("spid", js.getString("id"));
							String strId = js.getString("id");
							
							// 获取图片
							List<NameValuePair> ls1 = new ArrayList<NameValuePair>();
							ls1.add(new BasicNameValuePair("id", strId));
							Bitmap bitmap = HTTPGetTool.getTool()
									.queryByteForPost(
											URLUtils.HOST + URLUtils.SPXXPIC,
											ls1);
							map.put("pic", bitmap);
							list.add(map);
						}

						bundle.putInt("type", 2);
						bundle.putString("msg", "");
						pc += 1;
					} else {
						bundle.putInt("type", -1);
						bundle.putString("msg", "暂无数据");
					}

				} else {
					bundle.putInt("type", -1);
					bundle.putString("msg", "系统错误");
				}

			} else {
				bundle.putInt("type", -1);
				bundle.putString("msg", "网络连接失败!");
			}
			msg.setData(bundle);
			mUIHandler.sendMessage(msg);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			// 捕捉异常
			Bundle bundle = new Bundle();
			bundle.putInt("type", -1);
			bundle.putString("msg", e.toString());
			Message msg = mUIHandler.obtainMessage();
			msg.setData(bundle);
			mUIHandler.sendMessage(msg);
		}

	}

	private class MyAdapter extends BaseAdapter {
		private List<Map<String, Object>> list;
		private LayoutInflater mLayoutInflater;

		public List<Map<String, Object>> getList() {
			return list;
		}

		public void setList(List<Map<String, Object>> list) {
			this.list = list;
		}

		public MyAdapter(Context context) {
			mLayoutInflater = (LayoutInflater) context
					.getSystemService(LAYOUT_INFLATER_SERVICE);
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ViewHolder holder = null;
			if (convertView == null) {
				convertView = mLayoutInflater.inflate(R.layout.shop2_sub, null);
				holder = new ViewHolder();
				holder.gridview_imageview = (ImageView) convertView
						.findViewById(R.id.iv_img);
				holder.tv_name = (TextView) convertView
						.findViewById(R.id.tv_name);
				holder.tv_price = (TextView) convertView
						.findViewById(R.id.tv_price);
				holder.tv_dw = (TextView) convertView
						.findViewById(R.id.tv_dw);
				holder.tv_imgpath = (TextView) convertView
						.findViewById(R.id.tv_imgpath);
				holder.tv_lbid = (TextView) convertView
						.findViewById(R.id.tv_lbid);
				holder.tv_spid = (TextView) convertView
						.findViewById(R.id.tv_spid);
				holder.btn_buy = (Button) convertView
						.findViewById(R.id.btn_buy);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			holder.gridview_imageview.setImageBitmap((Bitmap) list
					.get(position).get("pic"));
			holder.tv_name.setText(list.get(position).get("name").toString());
			holder.tv_price.setText(list.get(position).get("price").toString());
			holder.tv_dw.setText(list.get(position).get("dw").toString());
			holder.tv_imgpath.setText(list.get(position).get("imgpath").toString());
			holder.tv_lbid.setText(list.get(position).get("lbid").toString());
			holder.tv_spid.setText(list.get(position).get("spid").toString());
			if (list_buy.contains(position)) {
				holder.btn_buy.setBackgroundDrawable(getResources().getDrawable(R.drawable.out_select));
				holder.btn_buy.setText("取消");
			} else {
				holder.btn_buy.setBackgroundDrawable(getResources().getDrawable(R.drawable.imageview_button));
				holder.btn_buy.setText("购买");
			}

			final Button buy = holder.btn_buy;
			final int location = position;
			buy.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if (list_buy.contains(location)) {
						int index = list_buy.indexOf(location);
						list_buy.remove(index);
					} else {
						list_buy.add(location);
					}
					syncroData();
					mAdapter.notifyDataSetChanged();

				}
			});

			return convertView;
		}
	}
	
	public class ViewHolder {
		private ImageView gridview_imageview;
		private TextView tv_name;
		private TextView tv_price;
		private TextView tv_dw;
		private TextView tv_imgpath;
		private TextView tv_lbid;
		private TextView tv_spid;
		private Button btn_buy;
	}

	// 同步到全局变量中
	private void syncroData() {
		if (list_buy.size() > 0) {
			list_gwc.clear();
			for (int i = 0; i < list_buy.size(); i++) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("pic", list.get(list_buy.get(i)).get("pic"));
				map.put("name", list.get(list_buy.get(i)).get("name")
						.toString().trim());
				map.put("price", list.get(list_buy.get(i)).get("price")
						.toString().trim());
				map.put("dw", list.get(list_buy.get(i)).get("dw")
						.toString().trim());
				map.put("imgpath", list.get(list_buy.get(i)).get("imgpath")
						.toString().trim());
				map.put("lbid", list.get(list_buy.get(i)).get("lbid")
						.toString().trim());
				map.put("spid", list.get(list_buy.get(i)).get("spid")
						.toString().trim());
				map.put("num", 1);
				list_gwc.add(map);
			}

		}
	}


	/* (non-Javadoc)
	 * @see android.widget.AdapterView.OnItemClickListener#onItemClick(android.widget.AdapterView, android.view.View, int, long)
	 */
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
	{
		// TODO Auto-generated method stub
		
	}
	
	
}
